import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 云梦归遥
 * @date 2021/11/18 11:53
 * @description
 */
public class ThreadTicketTest2   {


   static class SellTicketsThread extends Thread {
        private static int tickets = 100;
        private static final Lock lock = new ReentrantLock();

        public SellTicketsThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (tickets > 0) {
                    System.out.println(getName() + "正在卖第" + tickets + "张票，卖一张还剩" + --tickets + "张！");
                    lock.unlock();
                } else {
                    lock.unlock();
                    break;
                }
            }
        }
    }

    static  class Tickets implements Runnable {

        static int countTickets = 100;

        @Override
        public void run() {
            while (true) {
                synchronized (this) {
                    if (countTickets > 0) {
                        try {
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "卖票，票号是：" + countTickets);
                        countTickets--;
                    } else {
                        break;
                    }
                }
            }
        }
    }


    public static void main(String[] args) {
        Tickets tickets = new Tickets();

        Thread thread1 = new Thread(tickets, "窗口1");
        thread1.start();

        Thread thread2 = new Thread(tickets, "窗口2");
        thread2.start();

        Thread thread3 = new Thread(tickets, "窗口3");
        thread3.start();
    }



    public static void main2(String[] args) {

        SellTicketsThread t1 = new SellTicketsThread("线程1");
        SellTicketsThread t2 = new SellTicketsThread("线程2");
        SellTicketsThread t3 = new SellTicketsThread("线程3");
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
